<template>
    <div>
      <el-upload
        class="upload-demo"
        :action="actionUrl"
        :on-success="successHandler"
        :before-upload="beforeUpload"
        :on-exceed="handleExceed"
        multiple
        :limit="fileOptions.limit"
        :data="data"
        :headers="headers"
        :file-list="options.fileList"
      >
        <template #file="{ file }">
          <div class="custom-file-item" :key="file.id">
            <i class="el-icon-document" />
            <span class="file-name">{{ file.name }}</span>
            <el-button
              type="text"
              icon="el-icon-download"
              @click.stop="handleDownload(file)"
              v-if="file.id"
            />
            <el-button
              type="text"
              icon="el-icon-search"
              @click.stop="viewFile(file)"
              v-if="file.id"
            />
            <el-button
              type="text"
              icon="el-icon-close"
              @click.stop="deleteFile(file)"
              v-if="file.id && isEdit"
            />
          </div>
        </template>
        <el-button size="small" type="primary" v-if="isEdit">
          点击上传
        </el-button>
      </el-upload>
      <file-view-dialog :options="fileOptions" />
    </div>
  </template>
  
  <script lang="ts">
  import { Component, Prop, Vue, Watch, Emit } from 'vue-property-decorator';
  import store from '@/store';
  import FileViewDialog from '@/components/FileViewDialog.vue';
  
  interface FileItem {
    id: string;
    name: string;
    url?: string;
  }
  
  interface UploadOptions {
    url: string;
    fileList: FileItem[];
    removeApi?: (params: any) => Promise<any>;
  }
  
  @Component({
    components: { FileViewDialog }
  })
  export default class FileUploadComp extends Vue {
    @Prop({ required: true }) private options!: UploadOptions;
    @Prop() private dataId!: string;
    @Prop() private isEdit!: boolean;
  
    fileOptions: any = {
      dialogVisible: false,
      url: '',
      title: '',
      type: 'download',
      limit:5,

    };
  
    data: any = {
      id: ''
    };
  
    headers: any = {
      Authorization: 'Bearer ' + store.getters.token
    };
  
    get actionUrl() {
      return process.env.VUE_APP_BASE_API + this.options.url;
    }
  
    @Watch('dataId', { immediate: true })
    onDataIdChange(newVal: string) {
      this.data.id = newVal;
    }
  
    beforeUpload(file: File) {
      const isLt10M = file.size / 1024 / 1024 < 60;
      if (!isLt10M) {
        this.$message.error('文件大小不能超过 60MB');
      }
      return isLt10M;
    }

    viewFile(file){
        this.fileOptions.dialogVisible=true;
        this.fileOptions.type = file.name.split('.')[1]
    
        this.$set(this.fileOptions, 'url', process.env.VUE_APP_BASE_API +'/resources/file/' + file.id);
     
    }
  
    handleDownload(file: FileItem) {
        const link = document.createElement('a');

        link.href = process.env.VUE_APP_BASE_API +'/resources/file/' + file.id;
        link.setAttribute('download',file.name);
        link.click();
    }
    beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
    }

      handleExceed(files, fileList) {
          this.$message.warning(`当前限制选择${this.fileOptions.limit}个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      }
    async deleteFile(file: FileItem) {
      try {
        await this.beforeRemove(file, null);
        if (!this.options.removeApi) {
          throw new Error('未配置删除API');
        }
        
        const res = await this.options.removeApi({
          id: this.dataId,
          evidenceId: file.id
        });
  
        if (res.data && this.options.fileList  && this.options.fileList.length > 0) {
            this.options.fileList = this.options.fileList.filter(item => item.id !== file.id);
             this.$message.success(`文件 ${file.name} 删除成功`);
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(`文件删除失败`);
        }
      }
    }
  
    @Emit('update:file-list')
    successHandler(res: any, file: File, fileList: File[]) {
      let oldIds:any =[];
      if(!this.options.fileList){
        this.options.fileList =[];
      }else{
        oldIds =  this.options.fileList.map(item => item.id);
      }
        res.data.forEach(item =>{
            if(!oldIds.includes(item.id)){
                this.options.fileList.push(item);
            }
        })
    }
  }
  </script>
  
  <style scoped>
  .custom-file-item {
    display: flex;
    align-items: center;
    padding: 8px;
    border: 1px solid #ddd;
    margin-bottom: 4px;
    gap: 8px;
  }
  
  .file-name {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .el-button {
    margin-left: 8px;
    flex-shrink: 0;
  }
  </style>